package com.ruoyi.system.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.Student;
import com.ruoyi.system.domain.SysAnnounManagement;
import com.ruoyi.system.domain.SyseEventsPosted;
import com.ruoyi.system.domain.Work;
import com.ruoyi.system.domain.mongodb.*;
import com.ruoyi.system.mapper.StudentMapper;
import com.ruoyi.system.mapper.SysAnnounManagementMapper;
import com.ruoyi.system.mapper.SysEventsPostedMapper;
import com.ruoyi.system.mapper.WorkMapper;
import com.ruoyi.system.mongo.AllSchoolDao;
import com.ruoyi.system.mongo.StudentDao;
import com.ruoyi.system.mongo.WorksDao;
import com.ruoyi.system.service.IStudentService;
import com.ruoyi.system.service.IntepralSettingService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional
public class IStudentServiceImpl implements IStudentService {

    @Autowired
    private StudentDao studentDao;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private WorkMapper workMapper;

    @Autowired
    private WorksDao worksDao;

    @Autowired
    private SysEventsPostedMapper sysEventsPostedMapper;
    
    @Autowired
    private AllSchoolDao allSchoolDao;

    @Autowired
    private SysAnnounManagementMapper sysAnnounManagementMapper;

    @Autowired
    private IntepralSettingService intepralSettingService;

    /**
     * 根据id修改手机号信息(手机认证)
     * @param student
     */
    @Override
    public void updateStudnetPhoneNumById(Student student) {
        Users users =new Users();
        users.setId(student.getSid());
        users.setPhoneNum(student.getPhoneNum());
        studentDao.updatePhoneNumById(users);
        studentMapper.updateStudnetPhoneNumById(student);
    }

    /**
     * 根据大赛id查询参与该大赛的所有学生信息
     * @param epid
     * @return
     */
    @Override
    public List<Student> queryStudentsByEpid(Integer epid) {
        List<Student> studentList = null;
        if(epid!=0 || epid!=null){
            //获取学生信息集合
            List<Users> usersList = studentDao.selectUsersAlll();
            studentList =studentMapper.queryStudentsByEpid(epid);
//            if(studentList.size()!=0){
//                if(usersList.size()!=0){
//                        //循环
//                        for (Users users : usersList) {
//                            for (Student stu : studentList) {
//                                if (!StringUtils.isBlank(stu.getSid()) && !StringUtils.isBlank(users.getId())) {
//                                    //判断mongdb学生表id字段和student表的stuid字段是否对应
//                                    if (stu.getSid().equals(users.getId())) {
//                                        //替换nickname
//                                        stu.setSname(users.getNickname());
//                                    }
//                                }
//                            }
//                         }
//                }
//            }
        }
        return studentList;
    }

    /**
     *根据学校名称进行查询
     * */
    @Override
    public PageInfo<Users> selectBySchool(String schoolsName,Integer pageNum,Integer pageSize) {
        if(schoolsName.equals("请输入学校名称")){
            schoolsName = "";
        }
        PageInfo<Users> pageInfo = new PageInfo();
        //学校名称为空 查询全部
        if(StringUtils.isBlank(schoolsName)){
            pageInfo = studentDao.selectUsersByRole(0,pageNum,pageSize);
        }else {
            //根据学校名称查询出所有学校的id
            Schools school = studentDao.selectSchoolsByNames(schoolsName);
            if(school != null && school.getId() != ""){
                //根据学校的id查询出所有学生
                pageInfo = studentDao.selectUsersBySchool(school.getId(),0,pageNum,pageSize);
            }
        }
        if(pageInfo.getList().size() != 0){
            for (Users u:pageInfo.getList()){
                //根据学生的id  查询 学校的名称
                Schools schools = studentDao.selectSchoolsById(u.getSchool()==null?"":u.getSchool().toString());
                //设置学生的学校名称
                if(schools != null && schools.getNames() != null){
                    u.setSchoolName(schools.getNames());
                }
                //学生的班级不为空
                if(StringUtils.isNotEmpty(u.getClasslist()) && u.getClasslist().size() != 0){
                    String s = u.getClasslist().toString();
                    String ext = org.apache.commons.lang3.StringUtils.substringAfterLast(s, "=");
                    String classId = ext.substring(0,ext.length()-2);
                    //根据班级的id进行查询
                    Klasses klasse = studentDao.selectKlassesById(classId);
                    if(klasse != null && klasse.getClassname() != null){
                        u.setClassname(klasse.getClassname());
                    }
                }
            }
        }
        return pageInfo;
    }

    /**
     * 确认报名  根据学生的id进行查询
     * users： 报名的学生的 id  epId:赛事Id  teacher:指导老师
     * */
    @Override
    public Integer selectbyUserId(String users,String epId,String teacherId) {
        //查询老师信息
        Users teacher = studentDao.selectUsersByUserId(teacherId);
        //存放需要报名的学生
        List<Users> usersList = new ArrayList<>();
        Integer flag = 0;
        String[] split = users.split(",");
        if(split.length != 0){
            for(int i = 0;i<split.length;i++){
                String UserId = split[i];
                Users user = studentDao.selectUsersByUserId(UserId);
                usersList.add(user);
            }
        }
        //组装新的集合对象存放mysql数据库中去
        if(usersList.size() != 0){
            for(Users user:usersList){
                //去mysql中查询
                Integer integer = studentMapper.selectStudentByEidAndEpId(user.getId(), epId);
                //如果 该用户已报名该大赛  则不应该再继续报名了
                if(integer == 0){
                    Student student = new Student();
                    student.setSid(user.getId());//设置学生的id
                    student.setCreatetime(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",new Date()));//设置学生的报名时间
                    student.setEpId(epId); //设置报名的赛事id
                    student.setNickname(user.getNickname()); //设置昵称
                    //student.setOperatorId(users.getRealname()); //设置操作人的id(名称)(老师的id(名称))
                    student.setDirectTeacher(teacher.getRealname());  //设置指导老师名称
                    student.setRealname(user.getRealname());  //设置真实名称
                    student.setUsername(user.getUsername());//设置账号
                    student.setPhoneNum(user.getPhoneNum());//设置手机号
                    student.setQq(user.getQq());//qq
                    student.setWx(user.getWx());//微信
                    student.setEmail(user.getEmail());//设置邮箱
                    student.setSource(0);//设置报名来源
                    student.setTeacherId(teacherId);
                    //查询学生对应得学校
                    Schools school = studentDao.selectSchoolsById(user.getSchool()==null?"":user.getSchool().toString());
                    if(school != null && StringUtils.isNotEmpty(school.getNames())){
                        student.setSchooName(school.getNames());
                    }
                    //查询学生对应得班级
                    if(!CollectionUtils.isEmpty(user.getClasslist()) && user.getClasslist().size() != 0){
                        String s = user.getClasslist().toString();
                        String ext = org.apache.commons.lang3.StringUtils.substringAfterLast(s, "=");
                        String classId = ext.substring(0,ext.length()-2);
                        //根据班级的id进行查询
                        Klasses klasse = studentDao.selectKlassesById(classId);
                        if(klasse != null && klasse.getClassname() != null){
                            student.setClassName(klasse.getClassname());
                        }
                    }
                    flag = studentMapper.saveStudent(student);
                }
            }
        }
        return flag;
    }

    /**
     * 报名管理查询
     * eptitle：赛事标题
     * epsponsor 主办方
     * epstate 赛事状态
     * eplevel 赛事级别
     */
    @Override
    public List<SyseEventsPosted> selectEventsPostedAndAggregation(String eptitle, String epsponsor, String epstate, String eplevel,Integer pageNum,Integer pageSize) {
        if (pageNum!=null&&pageSize!=null){
            PageHelper.startPage((pageNum / pageSize) + 1,pageSize);
        }
        Map<String, Object> param = new HashMap<>(6);
        param.put("eptitle",eptitle);
        param.put("epsponsor",epsponsor);
        param.put("epstate",epstate);
        param.put("eplevel",eplevel);
        List<SyseEventsPosted> syseEventsPostedList = studentMapper.selectEventsPostedAndAggregation(param);
        return syseEventsPostedList;
    }

    /**
     * 报名管理查询
     * eptitle：赛事标题
     * epsponsor 主办方
     * epstate 赛事状态
     * eplevel 赛事级别
     */
    @Override
    public List<Student> selectEventsPostedForStudents(Student student,Integer pageNum,Integer pageSize) {
        if (pageNum!=null&&pageSize!=null){
            PageHelper.startPage((pageNum / pageSize) + 1,pageSize);
        }
        List<Student> studentList = studentMapper.selectEventsPostedForStudents(student);
        return studentList;
    }

    /**
     * 根据赛事下面的学生
     * epid 赛事的id
     * */
    @Override
    public List<Student> selectByEpIdAndEpstate(String epid,Integer pageNum,Integer pageSize) {
        if (pageNum!=null&&pageSize!=null){
            PageHelper.startPage((pageNum / pageSize) + 1,pageSize);
        }
        return studentMapper.selectByEpIdAndEpstate(epid);
    }

    @Override
    public Integer baoMingShenPi(String sid, String epId, int status) {
        return studentMapper.baoMingShenPi(sid, epId, status);
    }
    @Override
    public Integer piliangShenPi(List<Student> students) {
        int count = -1;
        for (Student student : students) {
            count += studentMapper.baoMingShenPi(student.getSid(), student.getEpId(), student.getStatus());
        }
        return count; //返回更新的行数
    }
    /**
     * 删除已经报名赛事得学生
     * */
    @Override
    public Integer deleteStudentBySid(String sid,String epId) {
        return studentMapper.deleteStudentBySid(sid,epId);
    }

    /**
     * 根据学校名称查询 指导老师
     * */
    @Override
    public List<Users> selectUsersByRole(String schoolName) {
        //根据学校名称查询
        Schools schools = studentDao.selectSchoolsByNames(schoolName);
        if(schools != null){
            //根据学校得id查询指导老师
            return studentDao.selectUsersBySchool02(schools.getId(),9);
        }
        return null;
    }

    /**
     * 根据学生ID查询他所参加的所有赛事和作品提交状态
     * @param userId  学生ID
     * @return
     */
    @Override
    public List<Map<String, Object>> selectEventsByUserID(String userId) {

        return studentMapper.selectEventsByUserID(userId);
    }

    /**
     * 根据老师ID查询他所参加的所有赛事和作品提交状态
     * @param teacherId  老师ID
     * @return
     */
    @Override
    public List<Map<String, Object>> selectEventsByTeacherID(String teacherId) {

        return studentMapper.selectEventsByTeacherID(teacherId);
    }

    /**
     * 根据老师所在得学校 查询这个学校下得所有学生
     * */
    @Override
    public PageInfo<Users> selectByTeacherSchool(String teacherId,Integer pageNum,Integer pageSize) {

        //根据老师的id 查询老师所在的学校的id
        Users users = selectByUserId(teacherId);
        PageInfo<Users> usersPage = null;
        if(users != null && null != users.getSchool() && StringUtils.isNotEmpty(users.getSchool().toString())){
            //获取到教师的id
            String schoolId = users.getSchool()==null?"":users.getSchool().toString();
            //根据教师的id 去查询该教师所在学校的学生
            usersPage = studentDao.selectUsersBySchool(schoolId, 0, pageNum, pageSize);
        }
        //判断查询到的学生不为空
        if(!CollectionUtils.isEmpty(usersPage.getList())){
            for (Users u:usersPage.getList()){
                //根据学生的id  查询 学校的名称
                Schools schools = studentDao.selectSchoolsById(u.getSchool()==null?"":u.getSchool().toString());
                //设置学生的学校名称
                if(schools != null && schools.getNames() != null){
                    u.setSchoolName(schools.getNames());
                }
                //学生的班级不为空
                if(!CollectionUtils.isEmpty(u.getClasslist())  && u.getClasslist().size() != 0){
                    String s = u.getClasslist().toString();
                    String ext = org.apache.commons.lang3.StringUtils.substringAfterLast(s, "=");
                    String classId = ext.substring(0,ext.length()-2);
                    //根据班级的id进行查询
                    Klasses klasse = studentDao.selectKlassesById(classId);
                    if(klasse != null && klasse.getClassname() != null){
                        u.setClassname(klasse.getClassname());
                    }
                }
            }
        }
        return usersPage;
    }

    /**
     * 老师端得学生批量报名
     * */
    @Transactional
    @Override
    public Integer teacherSaveStudent(String teacherId,String epid, String studentArr, String groupId) {
        //查询出指导老师的信息
        Users teacher = selectByUserId(teacherId);
        //根据id查询信息
        List<Users> usersList = new ArrayList<>();
        Integer flag = 0;
        int length = studentArr.length();
        studentArr = studentArr.substring(0,length-1);
        String[] split = studentArr.split(",");
        if(split.length != 0){
            for(int i = 0;i<split.length;i++){
                String UserId = split[i];
                Users user = studentDao.selectUsersByUserId(UserId);
                usersList.add(user);
            }
        }
        SyseEventsPosted syseEventsPosted = sysEventsPostedMapper.selectById(Integer.parseInt(epid));
        //组装新的集合对象存放mysql数据库中去
        if(!CollectionUtils.isEmpty(usersList)){
            for(Users user:usersList){
                //去mysql中查询 判断该用户是否重复报名该赛事
                Integer integer = studentMapper.selectStudentByEidAndEpId(user.getId(), epid);
                //如果 该用户已报名该大赛  则不应该再继续报名了
                if(integer == 0){
                    Student student = new Student();
                    student.setSid(user.getId());//设置学生的id
                    student.setCreatetime(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",new Date()));//设置学生的报名时间
                    student.setEpId(epid); //设置报名的赛事id
                    student.setNickname(user.getNickname()); //设置昵称
                    student.setOperatorId(teacher.getRealname()); //设置操作人的id(名称)(老师的id(名称))
                    student.setDirectTeacher(teacher.getRealname());  //设置指导老师名称
                    student.setRealname(user.getRealname());  //设置真实名称
                    student.setUsername(user.getUsername());//设置账号姓名
                    student.setPhoneNum(user.getPhoneNum());//设置手机号
                    student.setQq(user.getQq());//qq
                    student.setWx(user.getWx());//微信
                    student.setEmail(user.getEmail());//设置邮箱
                    student.setSource(1);
                    student.setTeacherId(teacherId);
                    student.setStatus(2); //报名状态不需要审批
                    student.setGroupId(groupId); //设置赛事小组ID
                    //查询学生对应得学校
                    Schools school = studentDao.selectSchoolsById(user.getSchool()==null?"":user.getSchool().toString());
                    if(school != null && StringUtils.isNotEmpty(school.getNames())){
                        student.setSchooName(school.getNames()); //设置学生的学校
                    }
                    //查询学生对应得班级
                    if(user.getClasslist().size() != 0){
                        String s = user.getClasslist().toString();
                        String ext = org.apache.commons.lang3.StringUtils.substringAfterLast(s, "=");
                        String classId = ext.substring(0,ext.length()-2);
                        //根据班级的id进行查询
                        Klasses klasse = studentDao.selectKlassesById(classId);
                        if(klasse != null && klasse.getClassname() != null){
                            student.setClassName(klasse.getClassname()); //设置学生的班级
                        }
                    }
                    if (StringUtils.isEmpty(syseEventsPosted.getEpstage())
                            || syseEventsPosted.getEpstage().indexOf("初赛")>-1 ) {
                        //初赛
                        student.setEvent_stage("初赛");
                    } else if (syseEventsPosted.getEpstage().equals("决赛")) {
                        student.setEvent_stage("决赛");
                    }
                    flag = studentMapper.saveStudent(student);
                }
            }
        }
        return flag;
    }
    @Transactional
    @Override
    public Integer applyStudentsByKlassId(String teacherId,String epid, String klassId, String groupId) {
        //查询出指导老师的信息
        Users teacher = selectByUserId(teacherId);
        Integer rows = 0;
        //查询赛事信息
        SyseEventsPosted syseEventsPosted = sysEventsPostedMapper.selectById(Integer.parseInt(epid));
        if (syseEventsPosted == null) {
            return rows;
        }
        //根据id查询信息
        List<Users> usersList = studentDao.selectUsersByClassId(klassId, 0);

        //组装新的集合对象存放mysql数据库中去
        if(!CollectionUtils.isEmpty(usersList)){
            //查询学生对应得学校
            Schools school = studentDao.selectSchoolsById(teacher.getSchool()==null?"":teacher.getSchool().toString());
            //根据班级的id进行查询
            Klasses klass = studentDao.selectKlassesById(klassId);
            for(Users user:usersList){
                //去mysql中查询 判断该用户是否重复报名该赛事
                Integer integer = studentMapper.selectStudentByEidAndEpId(user.getId(), epid);
                //如果 该用户已报名该大赛  则不应该再继续报名了
                if(integer == 0){
                    Student student = new Student();
                    student.setSid(user.getId());//设置学生的id
                    student.setCreatetime(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",new Date()));//设置学生的报名时间
                    student.setEpId(epid); //设置报名的赛事id
                    student.setNickname(user.getNickname()); //设置昵称
                    student.setOperatorId(teacher.getRealname()); //设置操作人的id(名称)(老师的id(名称))
                    student.setDirectTeacher(teacher.getRealname());  //设置指导老师名称
                    student.setRealname(user.getRealname());  //设置真实名称
                    student.setUsername(user.getUsername());//设置账号姓名
                    student.setPhoneNum(user.getPhoneNum());//设置手机号
                    student.setQq(user.getQq());//qq
                    student.setWx(user.getWx());//微信
                    student.setEmail(user.getEmail());//设置邮箱
                    student.setSource(1);
                    student.setTeacherId(teacherId);
                    student.setStatus(2); //报名状态不需要审批
                    student.setGroupId(groupId); //设置赛事小组ID
                    if(school != null && StringUtils.isNotEmpty(school.getNames())){
                        student.setSchooName(school.getNames()); //设置学生的学校
                    }
                    if(klass != null && klass.getClassname() != null){
                        student.setClassName(klass.getClassname()); //设置学生的班级
                    }

                    if (StringUtils.isEmpty(syseEventsPosted.getEpstage())
                            || syseEventsPosted.getEpstage().indexOf("初赛")>-1 ) {
                        //初赛
                        student.setEvent_stage("初赛");
                    } else if (syseEventsPosted.getEpstage().equals("决赛")) {
                        student.setEvent_stage("决赛");
                    }
                    rows += studentMapper.saveStudent(student);
                }
            }
        }
        return rows;
    }

    @Override
    public Users selectByUserId(String UserId) {
        Users users = studentDao.selectUsersByUserId(UserId);
        return users;
    }

    /**
     *  老师端：查询老师报名的学生
     * eptitle：赛事标题
     * epsponsor 主办方
     * epstate 赛事状态
     * eplevel 赛事级别
     * teacherId:教师id
     */
    @Override
    public List<Student> selectEventsAndAggreTeacher(Student student,Integer pageNum,Integer pageSize) {

        //根据老师的id查询学校的id
        if(StringUtils.isNotEmpty(student.getTeacherId())){
            Users users1 = studentDao.selectUsersByUserId(student.getTeacherId());
            String school = users1.getSchool()==null?"":users1.getSchool().toString();
            Schools schools = studentDao.selectSchoolsById(school);
            String epschool = schools.getNames();
            student.setSchooName(epschool); //添加学校名称
        }
        PageHelper.startPage(pageNum,pageSize);
        return studentMapper.selectEventsAndAggreTeacher(student);
    }

    /**
     * 根据学生的id 查询该学生没有发布的作品
     * */
    @Override
    public List<Works> selectWorksByUserId(String userId) {
        return studentDao.selectWorksByUserId(userId);
    }

    /**
     * 添加未发布的作品works   然后向mysql中的work表记录一下
     * userId:用户的id
     * epId：报名的赛事id
     * wordId：作品id
     * scratchId: 作品文件名称
     * */
    @Transactional
    @Override
    public Integer submitWorkForEvent(String userId, Integer epId, String wordId, Integer groupId) throws Exception {

        //查询作品信息
        Works works1 = worksDao.queryWorksById(wordId);
        if (works1 == null) {
            return 2; //如果作品文件无法找到，返回0
        }
        // 查询该赛事全部信息
        SyseEventsPosted syseEventsPosted = sysEventsPostedMapper.selectById(epId);
        if (StringUtils.isEmpty(syseEventsPosted.getEpstate()) || syseEventsPosted.getEpstate().equals("0") || syseEventsPosted.getEpstate().equals("2")) {
            return 3; //赛事进度不正常，当前未发布状态或已结束状态
        }
        //3.向mysql中插入  报名赛事的记录
        Work work = new Work();
        //设置当前赛事的进度
        if (StringUtils.isEmpty(syseEventsPosted.getProgressStatus())) {
            work.setScoring_step("初赛");
        } else {
           Integer progress = Integer.parseInt(syseEventsPosted.getProgressStatus());
            if (progress == 2) {
                work.setScoring_step("已结束");
            } else if (progress <= 4){
                work.setScoring_step("初赛");
            } else if (progress == 5){
                work.setScoring_step("复赛");
            } else if (progress == 6){
                work.setScoring_step("决赛");
            }
        }

        work.setWork_id(wordId);  //作品id
        work.setSid(userId);   //用户id
        work.setEpid(epId);   //赛事id
        work.setTitle(works1.getTitle());
        work.setWork_state("1"); //1代表参数作品， 0不是
        work.setAbstracts(works1.getAbstracts());
        work.setExplain(works1.getExplain());
        work.setWorksid(works1.getWorksid());//作品路径
        work.setCover_id(works1.getCovers()); //缩略图文件名
        work.setGroup_id(groupId); //设置赛事分组ID
        //2.查询mysql中的报名赛事的记录work表
        Map<String, String> param = new HashMap<>();
//        param.put("work_id",wordId);
        param.put("sid",userId);
        param.put("epid",epId.toString());
        param.put("scoring_step",work.getScoring_step());
//        param.put("group_id", groupId.toString());
        //判断该作品是否重复报名同一个赛事
        Work oldWork = workMapper.selectWorkByWorkIdAndSidAndEpId(param);

        if (oldWork != null) {
            //已提交过作品，把原来的作品删除掉再插入
            workMapper.deleteEpIdAndSid(userId, epId, work.getScoring_step());
        }

        Integer row = workMapper.saveWorks(work);
        //添加积分--提交作品
        intepralSettingService.addIntepral(userId, 7);
        return row;
    }

    /**
     * 根据userId  查询到用户所在学校的指导老师
     * */
    @Override
    public List<Users> selectUserById(String userId) {
        //1.查询
        Users user = studentDao.selectUsersByUserId(userId);
        if(user != null && user.getSchool()!=null){
            return studentDao.selectUsersBySchool02(user.getSchool().toString(),9);
        }
        return null;
    }

    /**
     * 学生端的赛事报名
     * */
    @Override
    public Integer saveStudent(Student student) {
        //根据id查询学生信息
        if(StringUtils.isEmpty(student.getSid())){
            return 2; //查无此学生
        }
        //查询报名赛事
        SyseEventsPosted syseEventsPosted = sysEventsPostedMapper.selectById(Integer.parseInt(student.getEpId()));
        //去mysql中查询  是否报名该赛事了
        Integer integer = studentMapper.selectStudentByEidAndEpId(student.getSid(), student.getEpId());
        if(integer == 1){ //已报名
            return 0;
        }
        //检查报名截止日期是否已过
        if (!StringUtils.isEmpty(syseEventsPosted.getEpsigend())) {
            Date endOfApply = null; //报名截止时间
            try {
                endOfApply = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(syseEventsPosted.getEpsigend());
                //比较日期
                if (endOfApply.getTime() < System.currentTimeMillis()) {
                    return 3; //报名时间已过期
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        //根据id查询老师信息
        Users teacher = selectByUserId(student.getTeacherId());
        System.out.println("teacher ==> " + teacher);
        //数据库中查询该用户信息
        Users user = studentDao.selectUsersByUserId(student.getSid());
        //如果 该用户已报名该大赛  则不应该再继续报名了
        Student studentNew = new Student();
        //复制student中的属性到 studentNew对象中
        BeanUtils.copyProperties(user, studentNew);

        studentNew.setSource(2); //报名来源  0管理员 1老师  2学生个人
        studentNew.setDirectTeacher(teacher.getRealname()); //设置老师得真实 名称
        studentNew.setTeacherId(teacher.getId()); //设置老师得id
        //复制student中的属性到 studentNew对象中
        BeanUtils.copyProperties(student, studentNew);
        studentNew.setCreatetime(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", new Date()));//设置学生的报名时间
        //报名是否需要审批的状态设置
        studentNew.setStatus(syseEventsPosted.getNeedApprove());
        if (StringUtils.isEmpty(syseEventsPosted.getEpstage())
                || syseEventsPosted.getEpstage().indexOf("初赛")>-1) {
            //初赛
            studentNew.setEvent_stage("初赛");
        } else if (syseEventsPosted.getEpstage().equals("决赛")) {
            studentNew.setEvent_stage("决赛");
        }

        //如果学校为空
        /*if (StringUtils.isEmpty(studentNew.getSchooName())) {
            //查询学生对应得学校
            Schools school = studentDao.selectSchoolsById(user.getSchool()==null?"":user.getSchool().toString());
            if (school != null && StringUtils.isNotEmpty(school.getNames())) {
                studentNew.setSchooName(school.getNames()); //设置学生的学校
            }
        }*/
        //查询学生对应得班级
        /*if (user.getClasslist().size() != 0) {
            String s = user.getClasslist().toString();
            String ext = org.apache.commons.lang3.StringUtils.substringAfterLast(s, "=");
            String classId = ext.substring(0, ext.length() - 2);
            //根据班级的id进行查询
            Klasses klasse = studentDao.selectKlassesById(classId);
            if (klasse != null && klasse.getClassname() != null) {
                studentNew.setClassName(klasse.getClassname()); //设置学生的班级
            }
        }*/
        try {
            //mysql保存报名信息
            Integer row = studentMapper.saveStudent(studentNew);
            //更新mongodb中的 User信息
            BeanUtils.copyProperties(studentNew, user);
            studentDao.updateUser(user);

            //添加积分--报名
            intepralSettingService.addIntepral(studentNew.getSid(), 6);
            return row;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }


    /**
     * 校园赛事公告
     * 根据学生的id  查询学生所在学校的校园级 manage
     * */
    @Override
    public List<SysAnnounManagement> selectManageByEpschoolAndEplevel(String userId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        //1.查询学生所在的学校
        Users users = studentDao.selectUsersByUserId(userId);
        //2.根据id 查询学校的名称
        AllSchool school = allSchoolDao.queryById(users.getSchool()==null?"":users.getSchool().toString());
        //3.根据学校名称 查询赛事
        List<SysAnnounManagement> sysAnnounManagementList = sysAnnounManagementMapper.selectManageByEpschoolAndEplevel(school.getNames(), "校园级");
        return sysAnnounManagementList;
    }


    /**
     * 校园赛事咨询
     * 根据学生的id  查询学生所在学校的校园级 的比赛
     * */
    @Override
    public List<SyseEventsPosted> selectEpByEpschoolAndEplevel(String userId,Integer pageNum,Integer pageSize) {
        //1.查询学生所在的学校
        Users users = studentDao.selectUsersByUserId(userId);
        //2.根据id 查询学校的名称
        AllSchool school = allSchoolDao.queryById(users.getSchool()==null?"":users.getSchool().toString());
        //3.根据学校名称 查询赛事
        PageHelper.startPage(pageNum,pageSize);
        List<SyseEventsPosted> syseEventsPostedList = sysEventsPostedMapper.selectEpschoolAndEplevel(school.getNames(), "校园级");
        //epprestart    epfinalend
        return syseEventsPostedList;
    }

    @Override
    public Users selectByUsersId(String userId) {
        return studentDao.selectUsersByUserId(userId);
    }

    /**
     * 删除报名赛事的作品
     * */
    @Override
    public Integer deleteUserIdAndWord(String userId, Integer epId) {
        //1.查询该赛事下的作品是不是再期限内  如果是期限内  则可以删除 期限外 不可以删除
        if(0 == 0){
            //因为 没有后面要使用work 的id  所以要先查询出来
            Work selectWork = workMapper.selectEpIdAndSid(userId, epId);
            //2. 删除mysql中的上传记录
            Integer workFlag = workMapper.deleteEpIdAndSid(userId, epId, null);
            //3.删除mongodb中的works表中的记录
            studentDao.deleteWorksById(selectWork.getWork_id());
            return 1;
        }
        return 0;
    }

    /**
     * 学生晋级下一阶段方法
     * @param epid
     * @param studentIds
     * @param eventStage
     * @return
     */
    @Transactional
    @Override
    public boolean upgradeNextStage(String epid, String studentIds, String eventStage) {
        String[] stuIdArr = null;
        if (studentIds.indexOf(",")>0) {
            stuIdArr = studentIds.split(",");
        } else {
            stuIdArr = new String[] {studentIds};
        }
        for (String sid : stuIdArr) {
            //更新学生报名信息的赛事阶段
            studentMapper.upgradeStudent(sid, epid, eventStage);
        }

        SyseEventsPosted syseEventsPosted = sysEventsPostedMapper.selectById(Integer.parseInt(epid));
        //下一阶段
        if ("初赛".equals(eventStage)) {
            syseEventsPosted.setProgressStatus("4");
        } else if ("复赛".equals(eventStage)) {
            syseEventsPosted.setProgressStatus("5");
        } else if ("决赛".equals(eventStage)) {
            syseEventsPosted.setProgressStatus("6");
        }
        //修改赛事阶段
        sysEventsPostedMapper.updateEpstate(syseEventsPosted);
        return true;
    }
}
